package org.shoukaiseki.aqoeous.controller;

import org.shoukaiseki.aqoeous.exception.ResultException;
import org.shoukaiseki.aqoeous.model.ResultModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import javax.servlet.http.HttpServletRequest;

/**
 * org.shoukaiseki.aqoeous.controller.ResultExceptionHandle
 * <br>
 *
 * @author 蒋カイセキ    Japan-Tokyo  19-2-11 下午4:38<br>
 * ブログ http://www.shoukaiseki.top/<br>
 * E-メール jiang28555@Gmail.com<br>
 **/
@ControllerAdvice
@EnableWebMvc
@Component
public class ResultExceptionHandle {

    private static Logger logger = LoggerFactory.getLogger(ResultExceptionHandle.class);

    @ResponseBody
    @ExceptionHandler({ResultException.class})
    public ResultModel resultException(HttpServletRequest request, Throwable e){
        logger.debug("",e);

        ResultModel result=exceptionToResultModel(e,null);

        return (result);
    }

    public static ResultModel exceptionToResultModel(Throwable t, Logger logger) {
        ResultModel resultModel = new ResultModel();
        if (t instanceof ResultException) {
            resultModel.setStatus(911);
            resultModel.setMsg(t.getMessage());
        } else {
            if (logger != null) {
                logger.error("-ResultModelUtils-", t);
            }

            resultModel.setStatus(911);
        }

        return resultModel;
    }
}
